package com.tuanzi.loan.web.bean.family.sms;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.DictionaryCode;
import com.tuanzi.loan.business.entity.family.ProductInfo;
import com.tuanzi.loan.business.entity.family.RegisterRecommendActivity;
import com.tuanzi.loan.business.entity.sms.*;
import com.tuanzi.loan.business.entity.statistics.ActivityChannelConfig;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.family.RegisterRecommendActivityService;
import com.tuanzi.loan.business.service.sms.PhoneLocationService;
import com.tuanzi.loan.business.service.sms.SmsCalculateTaskService;
import com.tuanzi.loan.business.service.sms.SmsSendTaskService;
import com.tuanzi.loan.business.service.sms.SmsUserDefinitionService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.vo.request.family.SmsCondition;
import com.tuanzi.loan.web.configuration.JSFBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;
import java.util.Map;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

@Data
@Slf4j
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class SmsConditionViewBean extends JSFBean {

	private SmsCondition smsCondition;
	private SmsCalculateTask smsCalculateTask;
	private SmsSendTask smsSendTask;

	private Integer activeIndex = 0;
	private Integer selectedTemplateGroup;
	private List<Dictionary> smsTemplates;
	private String template;
	private String activityName;
	private String var1;
	private String var2;
	private String var3;
	private String var4;

	@Autowired
	private RegisterRecommendActivityService registerRecommendActivityService;
	@Autowired
	private SmsCalculateTaskService smsCalculateTaskService;
	@Autowired
	private SmsSendTaskService smsSendTaskService;
	@Autowired
	private SmsUserDefinitionService smsUserDefinitionService;
	@Autowired
	private PhoneLocationService phoneLocationService;

	private List<SmsUserDefinition> smsUserDefinitions;
	private List<ProductInfo> productInfos;
	private List<RegisterRecommendActivity> activityTypes;
	private List<ActivityChannelConfig> activityChannelConfigs;
	private Map<String, String> provinces;
	private Map<String, String> firstPartyNames;

	@PostConstruct
	private void init() {
		activityTypes = registerRecommendActivityService.findAll();
		smsUserDefinitions = smsUserDefinitionService.findAll();

		String calculateTaskId = getParamFromRequest("calculateTaskId");
		if (StringUtils.isNotBlank(calculateTaskId)) {
			smsCalculateTask = smsCalculateTaskService.findOne(NumberUtils.toLong(calculateTaskId));
			smsCondition = GsonUtils.toObject(smsCalculateTask.getCondition(), SmsCondition.class);
		}

		String sendTaskId = getParamFromRequest("sendTaskId");
		if (StringUtils.isNotBlank(sendTaskId)) {
			smsSendTask = smsSendTaskService.findOne(NumberUtils.toLong(sendTaskId));
			smsCalculateTask = smsCalculateTaskService.findOne(smsSendTask.getCalculateTaskId());
			smsCondition = GsonUtils.toObject(smsCalculateTask.getCondition(), SmsCondition.class);
			provinces = phoneLocationService.findDistinctProvince();
			firstPartyNames = smsSendTaskService.findDistinctFirstNames();
		}
	}

	public String onSend() {
		return redirect("/views/family/user-info/send-sms/send-sms.xhtml?id=" + smsCalculateTask.getId());
	}

	public boolean canEditCalculateTask() {
		return smsCalculateTask != null && smsCalculateTask.getStatus() != SmsCalculateTaskStatus.CALCULATING
				&& smsCalculateTask.getStatus() != SmsCalculateTaskStatus.CALCULATE_DONE;
	}

	public boolean canEditSendTask() {
		return smsSendTask != null && smsSendTask.getStatus() != SmsSendTaskStatus.SENDING && smsSendTask.getStatus() != SmsSendTaskStatus.SEND_DONE;
	}

	public void onResend() {
		smsSendTask = smsSendTaskService.resend(smsSendTask.getId());
		addSuccessfullyMessage();
	}

	public void onSaveCalculateTask() {
		SmsCalculateTask dbSmsCalculateTask = smsCalculateTaskService.findOne(smsCalculateTask.getId());

		if (dbSmsCalculateTask != null && dbSmsCalculateTask.getStatus() != SmsCalculateTaskStatus.CALCULATING
				&& dbSmsCalculateTask.getStatus() != SmsCalculateTaskStatus.CALCULATE_DONE) {
			smsCalculateTaskService.saveOrUpdate(smsCalculateTask);
			addInfoMessage("保存计算任务成功");
		} else {
			addErrorMessage("计算任务保存失败, 状态已变更");
			smsCalculateTask = dbSmsCalculateTask;
		}
	}

	public void onSaveSendTask() {
		SmsSendTask dbSmsSendTask = smsSendTaskService.findOne(smsSendTask.getId());
		if (dbSmsSendTask != null && dbSmsSendTask.getStatus() != SmsSendTaskStatus.SENDING && dbSmsSendTask.getStatus() != SmsSendTaskStatus.SEND_DONE) {
			smsSendTaskService.saveOrUpdate(smsSendTask);
			addInfoMessage("保存发送任务成功");
		} else {
			addErrorMessage("发送任务保存失败, 状态已变更");
			smsSendTask = dbSmsSendTask;
		}
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(SMS_HIGH_QUALITY_USER_TYPE, SMS_ELIMINATE_BLACK_LIST, SMS_ELIMINATE_ACTION, SMS_ELIMINATE_ACTIVITY, SMS_USER_TYPE, PLATFORM, SMS_TEMPLATE_GROUP,
				SMS_TEMPLATE_BLACK_LIST, SMS_TEMPLATE_MARKETING, SMS_TEMPLATE_PULL_BACK, SMS_PLATFORM_CHANNEL, SMS_EXCLUDE_SENDED_DAY);
	}

	public void onSelectSmsTemplateGroup() {
		if (selectedTemplateGroup == null) {
			smsTemplates = Lists.newArrayList();
			return;
		}

		switch (selectedTemplateGroup) {
		case 1: // 甲方营销
			smsTemplates = getDictionaries().get(DictionaryCode.SMS_TEMPLATE_MARKETING);
			break;
		case 2:// 老用户回拉
			smsTemplates = getDictionaries().get(DictionaryCode.SMS_TEMPLATE_PULL_BACK);
			break;
		case 3:// 网贷黑名单
			smsTemplates = getDictionaries().get(DictionaryCode.SMS_TEMPLATE_BLACK_LIST);
			break;
		default:
			log.warn("switch条件不匹配 : {}", selectedTemplateGroup);
			break;
		}
	}

	public void onUpdateTemplate() {
		String content = StringUtils.EMPTY;

		content = StringUtils.replace(template, "{0}", StringUtils.isBlank(activityName) ? "菠萝贷" : activityName);
		content = StringUtils.replace(content, "{1}", var1);
		content = StringUtils.replace(content, "{2}", var2);
		content = StringUtils.replace(content, "{3}", var3);
		content = StringUtils.replace(content, "{4}", var4);
		smsSendTask.setContent(content);
	}

}
